package server

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"gitee.com/youbeiwuhuan/go-xxljob-executor/biz/model"
	"net/http"
	"runtime"
	"strings"
)

func Recovery(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			//打印错误堆栈信息
			//logger.GetLogger().Errorf("panic: %v\n", r)

			//s := printStackTrace(r)

			//Result.Fail不是本例的重点，因此用下面代码代替
			c.JSON(http.StatusOK, model.ReturnT{
				Code: model.FAIL_CODE,
				Msg:  fmt.Sprintf("panic: %v\n", r),
			})
			//终止后续接口调用，不加的话recover到异常后，还会继续执行接口里后续代码
			c.Abort()
		}
	}()
	//加载完 defer recover，继续后续接口调用
	c.Next()
}

// 打印堆栈信息
func printStackTrace(err interface{}) string {
	buf := new(bytes.Buffer)
	fmt.Fprintf(buf, "%v\n", err)
	for i := 1; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}

		if strings.Contains(file, "/go/") || strings.Contains(file, "/middleware/recovery.go") || strings.Contains(file, "/middleware/intercepter.go") {
			continue
		}
		fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
	}
	return buf.String()
}

func Deal404(c *gin.Context) {
	c.JSON(http.StatusOK, model.ReturnT{
		Code: model.FAIL_CODE,
		Msg:  fmt.Sprintf("path %s  dose not exist!", c.FullPath()),
	})
	c.Abort()
}
